'use strict';
const vkPay = require("vk-uni-pay");
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/yhsj/czjl/callback 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */

	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let {
			uid,
			out_trade_no,
			refund_desc,
			refund_fee,
		} = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------

		if (!userInfo.role.includes('agent')) {
			// res = { code: 1, msg: '操作失败！仅支持代理自己增加回传' };
			// return res;
		}
		
		let temp_info = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()
		var orderinfo = temp_info.data[0];
		let clickid = temp_info.data[0].clickid || "";
		
		//查询是否已经有回传记录
		let count_callback = await db.collection('jl_huichuanjilu').where({
			order_id: orderinfo._id
		}).count()
		
		if (count_callback.total > 0) {
			return { code: 2, msg: '已经回传过，不支持二次回传' };
		}

		if (orderinfo.tg_pt != "douyin") {
			return { code: 3, msg: '只支持抖音' };
		}
		//先获取用户表信息，如果用户信息里存在clud_token,则执行2.0回传接口
		let orderUser = await db.collection('uni-id-users').where({
			_id: orderinfo.user_id
		}).get();
		if (orderUser.data[0].clue_token) {
			const crypto = require('crypto');
			const sha1 = crypto.createHash('sha1');
	
			let url = "https://clue.oceanengine.com/outer/wechat/applet/token/1757233229756557";
			let nonce = 8889
			let token = "82A9DF19BD811D85ECA0DB54D13DC4A6";
			let times = vk.pubfn.toDecimal(new Date() / 1000, 0);
	
			let strList = [token, times, nonce];
			strList.sort();
			let buffer = "";
			strList.forEach(str => {
				buffer += str;
			})
			let sign = sha1.update(buffer).digest('hex');
			console.log("sign=", sign);
	
			let reback_url = url + "?timestamp=" + times + "&nonce=" + nonce + "&signature=" + sign;
	
			console.log("clue_token=", orderUser.data[0].clue_token);
			console.log("wx_openid=", orderUser.data[0].wx_openid['mp-weixin']);
	
			res.jlresult = await uniCloud.httpclient.request(reback_url, {
				method: 'POST',
				data: {
					"clue_token": orderUser.data[0].clue_token,
					"open_id": orderUser.data[0].wx_openid['mp-weixin'],
					"event_type": "2", //参考：https://bytedance.feishu.cn/docx/doxcnmjDmhXc1Vial05xpvdu9ed
					"props": {
						"pay_amount": refund_fee || 1 //单位：分
					}
				},
				contentType: 'json',
				dataType: 'json'
			})
			console.log("res.jlresult=", res.jlresult);
		} else {
			// 回传支付事件给巨量
			res.jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
			res.jlresult = await uniCloud.httpclient.request(res.jlurl, {
				method: 'POST',
				data: {
					"event_type": "active_pay",
					"context": {
						"ad": {
							"callback": clickid, //callback 这里需要填写的就是从启动参数里获取的 clickid
						}
					},
					"properties": {
						"pay_amount": refund_fee, //回传付费金额
					},
					//附加属性回传http://event-manager.oceanengine.com/docs/8650/all_properties/
					"timestamp": orderinfo._add_time
				},
				contentType: 'json',
				dataType: 'json'
			})
		}
	
		// 回传记录入库
		let addhc1 = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "douyin",
			order_id: orderinfo._id,
			user_id: orderinfo.user_id,
			tfid: orderinfo.tfid || "",
			aid: userInfo.aid || "",
			agent_id: orderinfo.invite_code || 0,
			middleman_id: orderinfo.middleman_id || 0,
			adid: orderinfo.ad_id,
			clickid: clickid,
			money: refund_fee,
			result: res.jlresult.data,
			time: orderinfo._add_time,
			time_str: orderinfo._add_time_str
		})
		
		res = { code: 0, msg: '回传成功' };

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
